package com.hu.common.util.sqlVal;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  SQL防注入验证器
 * </p>
 *
 * @author 63646
 * @since 2023/3/14
 */
public class CheckSqlInjectionValidator implements ConstraintValidator<CheckSqlInjection, Object> {
    @Override
    public void initialize(CheckSqlInjection constraintAnnotation) {

    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
        if (object == null) {
            return true;
        } else {
            return this.containsSqlInjection(object);
        }
    }

    /**
     * 是否含有sql注入，返回true表示含有
     *
     * @param obj
     * @return
     */
    public static boolean containsSqlInjection(Object obj) {
        Pattern pattern = Pattern.compile(
                "\\b(and|exec|insert|select|drop|grant|alter|delete|update|count|chr|mid|master|truncate|char|declare|or)\\b|(\\*|;|\\+|'|%)");
        Matcher matcher = pattern.matcher(obj.toString());
        return matcher.find();
    }
}
